<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学生信息管理系统 ｜ 登录注册</title>
    <link rel="stylesheet" href="css/form.css">
    <style>
        .errorMsg {
            color: red;
            font-weight: bold;
            font-family: 'Arial', sans-serif;
        }
    </style>
</head>
<body>
<div class="container">
    <h2>用户注册</h2>
    <span class="errorMsg"></span>
    <form id="registerForm">
        <input type="text" name="username" placeholder="用户名" required>
        <input type="password" name="password" placeholder="密码" required>
        <input type="email" name="email" placeholder="邮箱" required>
        <button type="submit">注册</button>
    </form>
    <div class="toggle-link">
        <p>已有账号？ <a href="/login.html">登录</a></p>
    </div>
</div>
<script>
    window.onload = () => {

        const registerForm = document.querySelector('#registerForm');
        const errorMsg = document.querySelector('.errorMsg');

        registerForm.addEventListener('submit', evt => {
            evt.preventDefault();
            errorMsg.innerHTML = '';
            const formData = new FormData(registerForm);

            const registerInfo = {};

            formData.forEach((value, key) => {
                registerInfo[key] = value;
            });

            register(registerInfo);
            return false;
        });

        const register = (registerInfo) => {
            fetch('dispatch.php?controller=StudentManage&service=register', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(registerInfo),

            })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 0) {
                        errorMsg.innerHTML = data.message;
                    } else {
                        // 处理成功进入首页
                        window.location.href = '/';
                    }
                })
        }

    };
</script>

</body>
</html>
